package fwk;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DispatchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BeanFactory bf;
       
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String fileName=config.getInitParameter("config");
		String applcationContextName=this.getServletContext().getRealPath("WEB-INF/"+fileName);
		bf=new BeanFactory(applcationContextName);
		
	}
    public DispatchServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path=getPath(request.getRequestURI());
		
		try {
			Controller c=((HandlerMapping)bf.getBean("handlerMapping")).mapController(path);
			ModelAndView mv=((HandlerAdapter)(bf.getBean("handlerAdapter"))).processHandler(c, request, response);
			
			((ViewResolver)bf.getBean("viewResolver")).render(mv, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	private String getPath(String s){
		int start=s.indexOf("/", 1);
		String path=s.substring(start);
		return path;
	}
	public static void main(String[] args) {
		
		
	}

}
